package com.ruoyi.system.service.aggregation.impl;

import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.aggregation.Account;
import com.ruoyi.system.domain.aggregation.SalesmanAudit;
import com.ruoyi.system.domain.aggregation.User;
import com.ruoyi.system.mapper.aggregation.AccountMapper;
import com.ruoyi.system.mapper.aggregation.SalesmanAuditMapper;
import com.ruoyi.system.mapper.aggregation.UserMapper;
import com.ruoyi.system.service.aggregation.ISalesmanAuditService;
import com.ruoyi.system.service.aggregation.ISalesmanNoService;

/**
 * 业务员审核Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-01-10
 */
@Service
public class SalesmanAuditServiceImpl implements ISalesmanAuditService 
{
    @Autowired
    private SalesmanAuditMapper salesmanAuditMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AccountMapper accountMapper;

    @Autowired
    private ISalesmanNoService salesmanNoService;

    private BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @Override
    public SalesmanAudit selectSalesmanAuditById(Long id)
    {
        return salesmanAuditMapper.selectSalesmanAuditById(id);
    }

    @Override
    public List<SalesmanAudit> selectSalesmanAuditList(SalesmanAudit salesmanAudit)
    {
        return salesmanAuditMapper.selectSalesmanAuditList(salesmanAudit);
    }

    @Override
    public int insertSalesmanAudit(SalesmanAudit salesmanAudit)
    {
        salesmanAudit.setStatue(1); // 默认待审核
        salesmanAudit.setCreateTime(DateUtils.getNowDate());
        return salesmanAuditMapper.insertSalesmanAudit(salesmanAudit);
    }

    @Override
    public int updateSalesmanAudit(SalesmanAudit salesmanAudit)
    {
        salesmanAudit.setUpdateTime(DateUtils.getNowDate());
        return salesmanAuditMapper.updateSalesmanAudit(salesmanAudit);
    }

    /**
     * 审核业务员
     * statue: 1待审核、2已通过、3已拒绝
     */
    @Override
    @Transactional
    public void checkSalesmanAudit(Long id, Integer statue, String reason)
    {
        SalesmanAudit audit = salesmanAuditMapper.selectSalesmanAuditById(id);
        if (audit == null)
        {
            throw new ServiceException("业务员审核记录不存在");
        }

        // 更新审核状态
        audit.setStatue(statue);
        audit.setReason(reason);
        audit.setUpdateTime(new Date());

        // 如果审核通过，创建业务员用户
        if (statue == 2)
        {
            // 检查该手机号是否已被注册为业务员（type=2）
            User existUser = userMapper.selectUserByPhoneAndType(audit.getPhone(), 2);
            if (existUser != null)
            {
                throw new ServiceException("该手机号已注册为业务员");
            }

            // ⭐ 生成8位业务员编号（审核通过后才生成）
            String salesmanNo = salesmanNoService.generateNextSalesmanNo();

            // 创建业务员用户
            User user = new User();
            user.setName(audit.getName());
            user.setType(2); // 业务员
            user.setPhone(audit.getPhone());
            user.setPassword(passwordEncoder.encode("123456")); // 默认密码
            user.setIdNo(audit.getIdNo());
            user.setAddress(audit.getAddress());
            user.setIdCardUrl(audit.getIdCardUrl());
            user.setIdCardBackUrl(audit.getIdCardBackUrl());
            user.setSalesmanNo(salesmanNo); // ⭐ 设置业务员编号
            user.setRegionId(audit.getRegionId());
            user.setDeleted(0);
            user.setCreateTime(new Date());
            user.setCreateBy(audit.getCreateBy());
            userMapper.insertUser(user);

            // 创建账户
            Account account = new Account();
            account.setUserId(user.getId());
            account.setBalance(0L);
            account.setTotalBalance(0L);
            account.setPeriod(DateUtils.dateTime(new Date()));
            account.setDeleted(0);
            account.setCreateTime(new Date());
            account.setCreateBy(audit.getCreateBy());
            accountMapper.insertAccount(account);

            // ⭐ 更新审核表的业务员编号字段
            audit.setSalesmanNo(salesmanNo);
        }

        // 更新审核记录
        salesmanAuditMapper.updateSalesmanAudit(audit);
    }

    @Override
    public int deleteSalesmanAuditByIds(Long[] ids)
    {
        return salesmanAuditMapper.deleteSalesmanAuditByIds(ids);
    }

    @Override
    public int deleteSalesmanAuditById(Long id)
    {
        return salesmanAuditMapper.deleteSalesmanAuditById(id);
    }
}

